/**
 *
 */
moduleMain.controller("DashboardLearningMapDetailReport", function ($stateParams, $timeout, LearningMapTemplateResource, LanguageService, $scope, $log, $state, DashboardResource, LoadingService, ConstantService, DialogService) {

    var myColors = ["#33414E", "#8DCA35", "#00BFDD", "#FF702A", "#DA3610",
        "#80CDC2", "#A6D969", "#D9EF8B", "#FFFF99", "#F7EC37", "#F46D43",
        "#E08215", "#D73026", "#A12235", "#8C510A", "#14514B", "#4D9220",
        "#542688", "#4575B4", "#74ACD1", "#B8E1DE", "#FEE0B6", "#FDB863",
        "#C51B7D", "#DE77AE", "#EDD3F2"];
    d3.scale.myColors = function () {
        return d3.scale.ordinal().range(myColors);
    };

    $scope.dateToString = function (d) {
        var year = d.getFullYear();
        var month = (d.getMonth() + 1).toString();
        var day = (d.getDate()).toString();
        if (month.length == 1) {
            month = "0" + month;
        }
        if (day.length == 1) {
            day = "0" + day;
        }
        return dateTime = year + "-" + month + "-" + day;
    }

    initPage($scope);
    $scope.$on("$viewContentLoaded", function () {
        $scope.reset();
        pageOnLoad($scope);
        $scope.currentState = $state.current;
        if ($scope.currentState.name === $state.current) {
            ConstantService.addState($state.current, true);
        }

        $scope.user = ConstantService.getItem('user');
        if ($stateParams.organizationClientId) {
            $scope.currentOrganizationClientId = $stateParams.organizationClientId;
        } else {
            $scope.currentOrganizationClientId = $scope.user.createOrgId;
        }

        $scope.queryLearningMap();
        // $scope.loadData();
    });

    $scope.reset = function () {
        $scope.queryPara = {
            from: $scope.dateToString(new Date(2018, 0, 1)),
            to: $scope.dateToString(new Date())
        }
        $scope.currentLearningMap = {};
    }

    $scope.queryLearningMap = function () {
        LearningMapTemplateResource.queryByOrganizationClient({pageNo: 0, pageSize: 50, publishStatus: 'RELEASED', organizationClientId: $scope.currentOrganizationClientId}, $scope.queryPara, function (queryResult) {
            $log.debug("查询结果", queryResult.data);
            $scope.learningMaps = queryResult.data.datas;
            $timeout(function () {
                $('#selectLearningMap').comboSelect();
            }, 1000);

            // $scope.loadData();
        });
    }

    $('#selectLearningMap').change(function (event) {
        // console.log(event.target.selectedIndex)
        // console.log(event.target.value)
        $scope.currentLearningMap.id = event.target.value;
    })

    $scope.selectLearningMap = function () {
        $scope.currentLearningMap.id = $scope.selectedLearningMap.id;
        $scope.currentLearningMap.name = $scope.selectedLearningMap.name;
        // $scope.loadData();
    }

    $scope.loadData = function () {

        // var params = new Object();
        // if($scope.queryPara.from && $scope.queryPara.to){
        //     params.from = $scope.queryPara.from;
        //     params.to = $scope.queryPara.to;
        // }
        var params = {};
        if ($scope.queryPara.from) {
            params.from = DateUtils.startTime($scope.queryPara.from).getTime();
        } else {
            params.from = DateUtils.startTime(new Date('2018-01-01')).getTime();
        }
        if ($scope.queryPara.to) {
            params.to = DateUtils.endTime($scope.queryPara.to).getTime();
        } else {
            params.to = DateUtils.endTime(new Date()).getTime();
        }
        //'b7cbb9d1-f5f2-4b5b-beed-007ea36c0239'
        DashboardResource.learningMapReport({learningMapId: $scope.currentLearningMap.id, organizationClientId: $scope.currentOrganizationClientId}, params, function (queryResult) {
            $log.debug("查询结果", queryResult.data);

            var reports = new Array();
            var currentReports = new Array();
            var titles = new Array();
            for (var i = 0; i < queryResult.data.courseDetailFunnelReports.length; i++) {
                var courseReport = queryResult.data.courseDetailFunnelReports[i];
                //titles
                titles.push(courseReport.learningMapCourseName);

                //
                // reports.push({
                //     value: courseReport.finishUserTotal,
                //     name: courseReport.learningMapCourseName,
                //     id: courseReport.learningMapCourseId,
                //     query: courseReport.query,
                //     current: false
                // });

                //
                currentReports.push({
                    value: courseReport.currentFinishUserTotal,
                    name: courseReport.learningMapCourseName,
                    id: courseReport.learningMapCourseId,
                    query: courseReport.query,
                    current: false
                });
            }


            report(currentReports, titles, queryResult.data.learningMapName, queryResult.data);
        });
    }

    var report = function (currentReports, titles, learningMapName, data) {
        // 基于准备好的dom，初始化echarts实例

        // 指定图表的配置项和数据
        option = {
            title: {
                text: LanguageService.language('地图漏斗'),
                subtext: learningMapName,
                left: 'center',
                top: 'top'
            },
            tooltip: {
                trigger: 'item',
                formatter: "{a} <br/>{b} : {c}"
            },
            toolbox: {
                feature: {
                    dataView: {readOnly: false},
                    restore: {},
                    saveAsImage: {}
                }
            },
            // legend: {
            //     data: titles,
            //     orient: 'vertical',
            //     left: 'right',
            //     top: 'bottom'
            // },
            series: [
                // {
                //     name: LanguageService.language('总完成数'),
                //     type: 'funnel',
                //     left: '10%',
                //     width: '80%',
                //     funnelAlign: 'left',
                //     label: {
                //         normal: {
                //             formatter: '{b}',
                //             textStyle: {
                //                 color: '#999999'
                //             }
                //         },
                //         emphasis: {
                //             position: 'inside',
                //             formatter: '{b}: {c}人'
                //         }
                //     },
                //     labelLine: {
                //         normal: {
                //             show: true
                //         }
                //     },
                //     itemStyle: {
                //         normal: {
                //             opacity: 0.7
                //         }
                //     },
                //     data: reports
                // },
                {
                    name: LanguageService.language('当前完成数'),
                    type: 'funnel',
                    left: '10%',
                    width: '80%',
                    maxSize: '80%',
                    funnelAlign: 'left',
                    label: {
                        normal: {
                            position: 'inside',
                            formatter: '{c}人',
                            textStyle: {
                                color: '#fff'
                            }
                        },
                        emphasis: {
                            position: 'inside',
                            formatter: '{b}: {c}人'
                        }
                    },
                    itemStyle: {
                        normal: {
                            opacity: 0.5,
                            borderColor: '#fff',
                            borderWidth: 2
                        }
                    },
                    data: currentReports
                }
            ]
        };
        var myChart1 = echarts.init(document.getElementById('report_1'), 'mb');
        // 使用刚指定的配置项和数据显示图表。
        myChart1.setOption(option);
        myChart1.on('click', function (params) {
            $state.go("sz.dashboardLearningMapAnswerCourseInfo", {
                query: encodeURIComponent(Base64.encode(JSON.stringify(params.data.query))),
                organizationClientId: $scope.currentOrganizationClientId
            });
        });
        report_2(data.courseDetailReports, learningMapName);
    }


    var report_2 = function (list, learningMapName) {
        var data = formatReport2Data(list);

        option = {
            title: {
                text: LanguageService.language('各环节完成情况百分比'),
                subtext: learningMapName,
                x: 'center'
            },
            tooltip: {
                trigger: 'item',
                formatter: "{a} <br/>{b} : {c} ({d}%)"
            },
            legend: {
                type: 'scroll',
                orient: 'vertical',
                right: 10,
                top: 20,
                bottom: 20,
                data: data.legendData,
                selected: data.selected
            },
            series: [
                {
                    name: LanguageService.language('章节'),
                    type: 'pie',
                    radius: '55%',
                    center: ['40%', '50%'],
                    data: data.seriesData,
                    itemStyle: {
                        emphasis: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }
            ]
        };

        var myChart2 = echarts.init(document.getElementById('report_2'), 'mb');
        // 使用刚指定的配置项和数据显示图表。
        myChart2.setOption(option);
    }


    var formatReport2Data = function (list) {
        var legendData = [];
        var seriesData = [];
        var selected = {};
        for (var i = 0; i < list.length; i++) {
            legendData.push(list[i].learningMapCourseName);
            seriesData.push({
                name: list[i].learningMapCourseName,
                value: list[i].finishUserTotal
            });
            selected[list[i].learningMapCourseName] = i < 6;
        }

        return {
            legendData: legendData,
            seriesData: seriesData,
            selected: selected
        };
    }

});